package dyyx.echo;

import dyyx.util.CommUtil;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

public class EchoServerHandler extends ChannelInboundHandlerAdapter {

	
	
	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		System.out.println("channelActive,remoteAddress=" + ctx.channel().remoteAddress()+",eventLoop="+ctx.channel().eventLoop());
	}
	
	@Override
	public void channelReadComplete(ChannelHandlerContext ctx) {
		ctx.flush();
	}

	@Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        System.out.println("msg="+msg);
        System.out.println("msg.info="+msg.getClass());
        
        String msgstr = msg.toString();
        
        if("fast".equals(msgstr)){
        	// no sleep
        }else{
        	
        	long sleep = CommUtil.getSleepTime(msgstr);
        	
        	// 模拟耗时
        	if(sleep>0){
                CommUtil.doSleep(sleep);
        	}
        }
        

        if("bye".equals(msg.toString())){
        	// write  vs  writeAndFlush
        	// channelReadComplete 里调用 flush
    		// ctx.writeAndFlush(msg+"\n").addListener(ChannelFutureListener.CLOSE);
    		ctx.write(msg+"\n").addListener(ChannelFutureListener.CLOSE);

        }if("error".equals(msg.toString())){
        	throw new RuntimeException("EchoServerHandler error");
        }else{
    		ctx.write(msg+"\n");
        }

    }
	
	

	
   

}
